package com.jrx.anytxn.atom.job.custBatch.step;

import com.jrx.anytxn.atom.bean.CustBatchSaveBean;
import com.jrx.anytxn.atom.service.IDealCustBatchService;
import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.redisson.service.RedissonLockService;
import com.jrx.anytxn.redisson.util.LockType;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustBatchWriter implements ItemWriter<CustBatchSaveBean> {

    Logger logger = LoggerFactory.getLogger(CustBatchWriter.class);

    @Autowired
    private IDealCustBatchService dealCustBatchService;
    @Autowired
    private RedissonLockService redissonLockService;
    @Autowired
    private RedisTemplate<String, Object> template;

    @Override
    public void write(List<? extends CustBatchSaveBean> items) throws Exception {
        try {
            dealCustBatchService.saveCustBeanForBatch((List<CustBatchSaveBean>) items);
        } finally {
            for (CustBatchSaveBean item : items) {
                CmCustomerFirstLevel firstLevel = item.getDealCust();
                String lockKey = String.format(TransBizConstant.CUST_BATCH_REDIS_LOCK, firstLevel.getTenantId(), firstLevel.getCustomerId());
                try {
                    logger.info("RedissionLock key:{}", lockKey);
                    RLock lock = redissonLockService.getRLock(lockKey, LockType.REENTRANT_LOCK);
                    if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                }catch (Exception e){
                    logger.error("RedissionLock unlock error key+:" + lockKey, e);
                }

            }
        }
    }

}
